<?php

namespace Cyfy\Modules\RelatedLinks;

use \Cyfy\Modules\Users\Current;
/**
 * RelatedLinks is a module for creating small blocks with header and hypertext link.
 * It's ideal for putting into columns / menus.
 *
 * @version 1.0
 * @author Dandelion
 */ 
class Module extends \Cyfy\Module
{
    static public $types = array(1 => "Související odkazy", 2=>"Související fotogalerie", 3=>"Související videa");
    
	/**
	 * AJAX method, returns result of AJAX call.
	 *
	 * @param string Name if the AJAX method.
	 * @return mixed String or array on success, False on fail.
	 */
	static function ajax($name)
	{
		// if no permission - return false
		if(!\Cyfy\Cyfy :: permission("RelatedLinks", "create and edit links"))
		{   
            \Cyfy\Cyfy :: noPermission();
			return false;
		}
	
		// else continue
		switch($name)
		{
			case "deleteLink":
				return self :: ajaxDeleteLink($_POST['lid']);
				break;
	
			case "editLink":
				return self :: ajaxEditLink($_POST['lid']);
				break;	
		}
		return false;
	}
	
	/**
	 * Block method, returns block when parameter $qcode called.
	 * If qcode not called, returns array of available blocks.
	 *
	 * @param string Code of the link
	 * @return mixed Array of blocks or content of the block
	 */
	static function blocks($name = "")
    {
		if($name)
		{
            if(\Cyfy\Blocks :: $forcedShow && strpos(\Cyfy\Cyfy :: $query, "Templates")){
                return "There will be some links here.";
            }
            $path = \Cyfy\Cyfy :: $query;
            
            
            
                
            
            
			// show block
			$result = \dibi :: query("SELECT * FROM [:cyfy:RelatedLinks] WHERE [path] = %s ORDER BY [type] ASC, [lid] DESC", $path);
            
            if(count($result) == 0 && !Current :: hasPermission("RelatedLinks", "create and edit links")) return "";
            
            
            $output .= "<div id=\"relatedLinks\">";
			$previous = 0;
            // block found
            foreach($result as $link)
            {
            
                // should we use internal / external address?
                if(preg_match("/http:\/\//", $link["link"])){
                    $url = $link["link"];
                }else{
                    $url = \Cyfy\Cyfy ::  getPath($link["link"]);
                }
                
                $edit = "";
                // admin?
                if(Current :: hasPermission("RelatedLinks", "write and edit"))
                {
                    $edit = "<input type=\"submit\" value=\"E\" onclick=\"Cyfy.ajax('RelatedLinks', 'editLink', '#relatedLinks', 'lid={$link["lid"]}');\" /> ";
                    $edit .= "<input type=\"submit\" value=\"X\" class=\"button-warning\" onclick=\"if(confirm('" . self :: t(41, array($link["name"])) . "')){ Cyfy.ajax('RelatedLinks', 'deleteLink', '', 'lid={$link["lid"]}', 'Blocks.reload(\'RelatedLinks\', \'links\');');} return false;\" />";
                }
                $caption = "";
                if($previous != $link["type"])
                {
                    if($previous!=0)
                    {
                        $output .= "</ul>";
                    }
                    $caption = "<li><h3>" . self :: $types[$link["type"]]. "</h3> <ul>";
                }
                $previous = $link["type"];
                // block
                $output .= <<<OUTPUT
    {$caption}
        <li class="link">
            <a href="{$url}">{$link["name"]}</a> {$edit}
        </li>		
OUTPUT;
            }
            $output .=" </li></ul>   </div>		";
            
            if(Current :: hasPermission("RelatedLinks", "create and edit links"))
            {
                $form = new Forms\Create(true);
                $form -> path = \Cyfy\Cyfy :: $query;
                $form -> structure();
                $c = new \Cyfy\Modules\Objects\Collapsible();
                $c -> setData(self :: t(80), $form ->show(), true);
                $output .= $c -> show();
            }
            return $output;
        }

        // show list
        return array("links" => self :: t(10));
    }
	
	/**
	 * AJAX call for link edit.
	 *
     * @param int QuickLink ID
	 * @return Form for editing.
	 */
	static function ajaxEditLink($lid)
	{
		$result = \dibi :: query("SELECT * FROM [:cyfy:RelatedLinks] WHERE [lid] = %i", $lid);
		
		if(count($result) != 0)
		{
			// link found - get data
			$l = $result->fetch();
			
			// form
			$form = new Forms\Edit();
			$form -> setData($l);
			$form -> setTemp("lid", $l["lid"]);
			
			return "<h2>" .self :: t(61, array($l["name"])) . "</h2>\n" . $form -> show();
		}
		else
		{
			return "";
		}
	}
	
	/**
	 * AJAX call for link delete.
	 *
     * @param int QuickLink ID
	 * @return List of links after deleting
	 */
	static private function ajaxDeleteLink($lid)
	{
		\dibi :: query("DELETE FROM [:cyfy:RelatedLinks] WHERE [lid] = %i", $lid);
		\Cyfy\Message :: set( self :: t(70));
		return true;
	}
	
}
